const {
    override,
    addLessLoader,
    addWebpackAlias,
    overrideDevServer
} = require("customize-cra");
const path = require("path");
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const rewireReactHotLoader = require("react-app-rewire-hot-loader");
const multipleEntry = require("react-app-rewire-multiple-entry")([
    {name: "index", entry: "src/index.tsx", template: "public/index.html", outPath: "/index.html"},
    {
        entry: "src/entry/design/index.tsx",
        template: "src/entry/design/design.html",
        outPath: "/design.html"
    },
    {
        entry: "src/entry/preview/index.tsx",
        template: "src/entry/preview/preview.html",
        outPath: "/preview.html"
    },
]);
const isEnvProduction = process.env.NODE_ENV === "production";
if (isEnvProduction) process.env.GENERATE_SOURCEMAP = "false";
// 设置打包路径
const setBuildPath = () => config => {
    config.output.publicPath = "./";
    return config;
};
const addCompression = () => config => {
    if (isEnvProduction) {
        config.plugins.push(
            // gzip压缩
            new CompressionWebpackPlugin({
                test: /\.(css|js)$/,
                // 只处理比100kb大的资源
                threshold: 102400,
                // 只处理压缩率低于90%的文件
                minRatio: 0.9

            })
        );
    }
    return config;
};
// 添加热更新
const addHotLoader = () => config => {
    config = rewireReactHotLoader(config);
    return config;
};
const devServerConfig = () => config => {
    return {
        ...config,
        port: 3000,
        proxy: {
            "/api/": {
                target: "http://localhost:3000/",
                changeOrigin: true,
                secure: false,
                xfwd: false
            }
        }
    };
};
module.exports = {
    webpack: override(
        multipleEntry.addMultiEntry,
        addHotLoader(),
        setBuildPath(),
        addLessLoader({
            lessOptions: {
                modifyVars: {"@primary-color": "#2196f3"},
                javascriptEnabled: true
            }
        }),
        addCompression(),
        addWebpackAlias(
            {"@": path.resolve(__dirname, "src")},
            {"react": path.resolve("./node_modules/react")},
            {"react-dom": "@hot-loader/react-dom"}
        )
    ),
    devServer: overrideDevServer(
        devServerConfig()
    )
};
